package com.wss.controller;

import com.alibaba.fastjson.JSON;
import com.wss.domain.*;
import com.wss.service.CommentService;
import com.wss.service.OrderService;
import com.wss.service.VideoService;
import com.wss.service.VideoTypeService;
import com.wss.util.FileUploadUtil;
import org.apache.commons.io.FilenameUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.File;
import java.io.IOException;
import java.util.List;
import java.util.UUID;

@Controller
public class VideoController {

    @Autowired
    private VideoService videoService;
    @Autowired
    private VideoTypeService videoTypeService;
    @Autowired
    private OrderService orderService;
    @Autowired
    private CommentService commentService;

    /**
     * 展示视频主页
     * @param request
     * @param response
     * @return
     */
    @RequestMapping(value="/videoMain")
    public ModelAndView videoMain(Model model,HttpServletRequest request, HttpServletResponse response){
        // 布置视频分类菜单
        initVideoType(model);
        // 查询最新8条视频信息
        List<Video> videoList = videoService.findVideoTop8();
        model.addAttribute("videoList",videoList);
        VideoType videoType = new VideoType();
        videoType.setVtypename("最新视频");
        model.addAttribute("videoType",videoType);
        return new ModelAndView("videoMain");
    }

    /**
     * 从分类按钮searchVideo查询结果异步加载到页面内
     */
    @RequestMapping(value="/searchVideo",method=RequestMethod.GET)
    public String searchVideo(int vtype_id,Model model){
        // 布置视频分类菜单
        initVideoType(model);
        List<Video> videoList = videoService.findVideoByTypeId(vtype_id);
        VideoType videoType = videoTypeService.findVtypeNameByVtypeid(vtype_id);
        model.addAttribute("videoList",videoList);
        model.addAttribute("videoType",videoType);
        return "videoMain::video_searchres";
    }

    /**
     * 搜索框模糊查询视频
     */
    @RequestMapping(value="/searchInputVideo")
    public ModelAndView searchInputVideo(@RequestParam("searchText") String searchText, Model model){
        // 布置视频分类菜单
        initVideoType(model);
        searchText = searchText.trim();
        // 模糊查询视频信息
        List<Video> videoList = videoService.findVideoBySearchInput(searchText);
        model.addAttribute("videoList",videoList);
        VideoType videoType = new VideoType();
        videoType.setVtypename("查询“"+searchText+"”搜索结果");
        model.addAttribute("videoType",videoType);
        return new ModelAndView("videoMain");
    }


    /**
     * 视频详情页
     * 用RedirectAttributes，这个是发现的一个比较好用的一个类
     * 用它的addAttribute方法，这个实际上重定向过去以后你看url，是它自动给你拼了你的url。
     */
    @RequestMapping(value="/videoDetail",method=RequestMethod.GET)
    public String videoDetail(int v_id, Model model, RedirectAttributes attr, HttpServletRequest request, HttpServletResponse response){
        // 根据视频id和用户id判断是否已购买课程
        HttpSession session = request.getSession();
        Account account = (Account) session.getAttribute("Account");
        // 从session中拿到当前用户id封装到Order对象中
        int u_id = account.getId();
        Order order = new Order();
        order.setU_id(u_id);
        order.setV_id(v_id);
        Order orderRes = orderService.findOrderByUidnVid(order);
        if (orderRes == null){
            System.out.println("用户未购买此课程进入购买页面");
            //如果返回的订单查询结果是空的，就跳转到购买界面
            attr.addAttribute("u_id",u_id);
            attr.addAttribute("v_id",v_id);
            return "redirect:orderPage";
        }else{
            Video video = videoService.findVideoById(v_id);
            //根据v_id查询出博客的所有评论
            List<Comment> commentList = commentService.findCommentByVideoId(v_id);
            model.addAttribute("video",video);
            model.addAttribute("commentList",commentList);
            return "videoDetail";
        }
    }

    /**
     * 布置视频分类菜单
     */
    public void initVideoType(Model model){
        List<VideoType> qianduanList = videoTypeService.findVideoTypeByVthid(1);
        List<VideoType> houduanList = videoTypeService.findVideoTypeByVthid(2);
        List<VideoType> shujukuList = videoTypeService.findVideoTypeByVthid(3);
        List<VideoType> wangluoList = videoTypeService.findVideoTypeByVthid(4);
        model.addAttribute("qianduanList",qianduanList);
        model.addAttribute("houduanList",houduanList);
        model.addAttribute("shujukuList",shujukuList);
        model.addAttribute("wangluoList",wangluoList);
    }

    /**
     * 添加视频
     */
    @RequestMapping(value="/addVideo")
    public String addVideo(Video video, MultipartFile vcoverfile, MultipartFile videofile, HttpServletRequest request) throws IOException {
        System.out.println("==============进入到/addVideo=============");
        //创建文件上传工具类对象，调用上传方法并返回文件保存的路径
        FileUploadUtil fileUploadUtil = new FileUploadUtil();
        String vcoverUrl = fileUploadUtil.uploadImage(vcoverfile,request);
        String videoUrl = fileUploadUtil.uploadVideo(videofile,request);
        //把图片存储路径放入到video对象中保存到数据库
        video.setVcoverurl(vcoverUrl);
        video.setVurl(videoUrl);
        videoService.addVideo(video);
        //刷新admin主页
        return "redirect:indexAdmin";
    }

    /**
     * 修改视频信息
     */
    @RequestMapping(value="/changeVideo")
    public String changeVideo(Video video, MultipartFile vcoverfile, MultipartFile videofile, HttpServletRequest request) throws IOException {
        System.out.println("==============进入到/changeVideo=============");
        //创建文件上传工具类对象，调用上传方法并返回文件保存的路径
        FileUploadUtil fileUploadUtil = new FileUploadUtil();
        String vcoverUrl = fileUploadUtil.uploadImage(vcoverfile,request);
        String videoUrl = fileUploadUtil.uploadVideo(videofile,request);
        //把图片存储路径放入到video对象中保存到数据库
        video.setVcoverurl(vcoverUrl);
        video.setVurl(videoUrl);
        videoService.changeVideo(video);
        //刷新admin主页
        return "redirect:indexAdmin";
    }

    /**
     * 删除视频
     */
    @RequestMapping(value="/deleteVideo", method= RequestMethod.POST, produces = {"application/json;charset=UTF-8"})
    @ResponseBody
    public String deleteVideo(Video video){
        System.out.println("==============进入到/deleteVideo=============");
        // 返回给前端的信息对象
        Message message = videoService.deleteVideo(video.getId());
        String msg = JSON.toJSONString(message);
        return msg;
    }


}
